﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Threading;
using System.Collections;

namespace INSAForManagers
{
    public partial class FormCareer : Form
    {
        private FormACard formParent;
        private string fileName;
        private DataTable tbl;

        public FormCareer(FormACard parent)
        {
            InitializeComponent();
            this.formParent = parent;
            Control.CheckForIllegalCrossThreadCalls = false;
            tbl = new DataTable();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lnkXlsRead_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "엑셀 파일(*.xls) | *.xls";
            dlg.Multiselect = false;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                fileName = dlg.FileName;
                readXlsList();
            }

            lnkSave.Enabled = false;
        }

        private void readXlsList()
        {
            try
            {
                clearDGV();

                Util.openXls(fileName);
                Util.changeSheet(3);

                Excel.Range range;

                range = Util.OSheet.get_Range("A5", "G30");

                object[,] val = (object[,])range.get_Value(Missing.Value);

                for (int i = 1; i <= val.GetUpperBound(0); i++)
                {
                    if (val[i, 1] == null)
                    {
                        Util.closeXls();
                        return;
                    }

                    DataRow row = tbl.NewRow();
                    row[0] = val[i, 1].ToString().Trim();//종류
                    row[1] = val[i, 2].ToString().Trim();//등급
                    row[2] = val[i, 3].ToString();//근무지
                    row[3] = DateTime.Parse(val[i, 4].ToString());//근무시작
                    row[4] = DateTime.Parse(val[i, 5].ToString());//근무마침
                    if (val[i, 6] != null && val[i, 7] != null)
                    {
                        row[5] = DateTime.Parse(val[i, 6].ToString());//제외시작
                        row[6] = DateTime.Parse(val[i, 7].ToString());//제외마침
                        int[] diff = Util.getMonthCount(DateTime.Parse(val[i, 4].ToString()), DateTime.Parse(val[i, 6].ToString()), DateTime.Parse(val[i, 5].ToString()), DateTime.Parse(val[i, 7].ToString()));

                        row[7] = diff[0];//근무 월수
                        row[8] = diff[1];//근무 일수
                    }
                    else
                    {
                        row[5] = DateTime.Parse("1900-01-01");//제외시작
                        row[6] = DateTime.Parse("1900-01-01");//제외마침
                        int[] diff = Util.getMonthCount(DateTime.Parse(val[i, 4].ToString()), DateTime.Parse(val[i, 5].ToString()));
                        row[7] = diff[0];//근무 월수
                        row[8] = diff[1];//근무 일수
                    }

                    row[9] = Util.getCareerMonthPoint(row[0].ToString(), row[1].ToString());
                    row[10] = Util.getCareerDayPoint(row[0].ToString(), row[1].ToString());
                    row[11] = (double)row[9]*(int)row[7] + (double)row[10]*(int)row[8];

                    tbl.Rows.Add(row);
                }

                dgvCareerList.DataSource = tbl;

                range = null;
                Util.closeXls();

                lnkSave.Enabled = false;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인");
                Util.closeXls();
            }
        }

        private void clearDGV()
        {
            tbl.Rows.Clear();
            dgvCareerList.DataSource = tbl;
        }

        private void FormCareer_Load(object sender, EventArgs e)
        {
            try
            {
                addColumns();

                initGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인");
            }
        }

        private void addColumns()
        {
            DataColumn col = null;

            //경력종류
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "경력종류";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //경력등급
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "경력등급";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //근무지명
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");            
            col.ColumnName = "근무지명";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //재직기간_시작
            col = new DataColumn();
            col.DataType = Type.GetType("System.DateTime");
            col.ColumnName = "재직기간(시작)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //재직기간_끝
            col = new DataColumn();
            col.DataType = Type.GetType("System.DateTime");
            col.ColumnName = "재직기간(마침)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //제외기간_시작
            col = new DataColumn();
            col.DataType = Type.GetType("System.DateTime");
            col.ColumnName = "제외기간(시작)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //제외기간_끝
            col = new DataColumn();
            col.DataType = Type.GetType("System.DateTime");
            col.ColumnName = "제외기간(마침)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //평정월수
            col = new DataColumn();
            col.DataType = Type.GetType("System.Int32");
            col.ColumnName = "평정월수";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //평정일
            col = new DataColumn();
            col.DataType = Type.GetType("System.Int32");
            col.ColumnName = "평정일수";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //월평정점
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "월평정점";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //월평정점
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "일평정점";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //평정점
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "평정점";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            dgvCareerList.DataSource = tbl;

            dgvCareerList.Columns[0].Width = 70;
            dgvCareerList.Columns[1].Width = 60;
            dgvCareerList.Columns[2].Width = 120;
            dgvCareerList.Columns[3].Width = 70;
            dgvCareerList.Columns[4].Width = 70;
            dgvCareerList.Columns[5].Width = 70;
            dgvCareerList.Columns[6].Width = 70;
            dgvCareerList.Columns[7].Width = 70;
            dgvCareerList.Columns[7].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvCareerList.Columns[8].Width = 60;
            dgvCareerList.Columns[8].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvCareerList.Columns[9].Width = 60;
            dgvCareerList.Columns[9].DefaultCellStyle.Format = "#0.0000";
            dgvCareerList.Columns[9].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvCareerList.Columns[10].Width = 60;
            dgvCareerList.Columns[10].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvCareerList.Columns[10].DefaultCellStyle.Format = "#0.0000";
            dgvCareerList.Columns[11].Width = 60;
            dgvCareerList.Columns[11].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvCareerList.Columns[11].DefaultCellStyle.Format = "#0.0000";

        }

        private void initGrid()
        {
            string pcode = formParent.txtPCode.Text;
            if (pcode.Equals(""))
            {
                MessageBox.Show("대상자를 입력 후에 다시 시도하세요!   ", "확인");
                this.Close();
                return;
            }

            ArrayList list = DBUtil.getListFromCareerTable(pcode);
            for (int i = 0; i < list.Count; i++) 
            {
                ArrayList data = (ArrayList)list[i];

                DataRow row = tbl.NewRow();
                row[0] = (string)data[2];
                row[1] = (string)data[3];
                row[2] = (string)data[4];
                row[3] = (DateTime)data[5];
                row[4] = (DateTime)data[6];

                if (!data[7].ToString().Equals("1900-01-01"))
                {
                    row[5] = (DateTime)data[7];
                    row[6] = (DateTime)data[8];
                }
                row[7] = (int)data[9];
                row[8] = (int)data[10];
                row[9] = (double)data[11];
                row[10] = (double)data[12];
                row[11] = (double)data[13];

                tbl.Rows.Add(row);
            }

            dgvCareerList.DataSource = tbl;

            for (int j = 0; j < list.Count; j++)
            {
                dgvCareerList.Rows[j].DefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
            }
            
        }

        private void lnkCalcEvalue_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //총월수 점수
            double[] total_month_point = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };

            //총일수 점수
            double[] total_day_point = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };

            //총점 저장 배열
            double[] total_point = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };

            //구분-등급별 월수
            int[,] total_month = new int[2, 3];

            //구분-등급별 일수
            int[,] total_day = new int[2, 3];
            
            //평정 월수 누계
            int careerMonth = 0;

            //평정 일수 누계
            int careerDay = 0;
            
            //DataGridView의 모든 행에 대해 구분-등급별 월수 및 일수와 총월수 및 총일수를 계산한다.
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                if (tbl.Rows[i][0].ToString().Equals("기본경력"))
                {
                    if (tbl.Rows[i][1].ToString().Equals("가경력"))
                    {
                        total_month[0, 0] += Int32.Parse(tbl.Rows[i][7].ToString());
                        careerMonth += total_month[0, 0];

                        total_day[0, 0] += Int32.Parse(tbl.Rows[i][8].ToString());
                        careerDay += total_day[0, 0];

                    }
                    else if (tbl.Rows[i][1].ToString().Equals("나경력"))
                    {
                        total_month[0, 1] += Int32.Parse(tbl.Rows[i][7].ToString());
                        careerMonth += total_month[0, 1];

                        total_day[0, 1] += Int32.Parse(tbl.Rows[i][8].ToString());
                        careerDay += total_day[0, 1];

                    }
                    else
                    {
                        total_month[0, 2] += Int32.Parse(tbl.Rows[i][7].ToString());
                        careerMonth += total_month[0, 2];

                        total_day[0, 2] += Int32.Parse(tbl.Rows[i][8].ToString());
                        careerDay += total_day[0, 2];

                    }
                }
                else
                {
                    if (tbl.Rows[i][1].ToString().Equals("가경력"))
                    {
                        total_month[1, 0] += Int32.Parse(tbl.Rows[i][7].ToString());
                        careerMonth += total_month[1,0];

                        total_day[1, 0] += Int32.Parse(tbl.Rows[i][8].ToString());
                        careerDay += total_day[1, 0];

                        
                    }
                    else if (tbl.Rows[i][1].ToString().Equals("나경력"))
                    {
                        total_month[1, 1] += Int32.Parse(tbl.Rows[i][7].ToString());
                        careerMonth += total_month[1, 1];

                        total_day[1, 1] += Int32.Parse(tbl.Rows[i][8].ToString());
                        careerDay += total_day[1, 1];

                    }
                    else
                    {
                        total_month[1, 2] += Int32.Parse(tbl.Rows[i][7].ToString());
                        careerMonth += total_month[1, 2];

                        total_day[1, 2] += Int32.Parse(tbl.Rows[i][8].ToString());
                        careerDay += total_day[1, 2];

                    }
                }
            }

            if (total_day[0, 0] >= 30)
            {
                if(total_day[0, 0] == 30 || total_day[0, 0] == 31){
                    total_month[0, 0]++;
                    total_day[0, 0] = 0;
                }

                if (total_day[0, 0] > 31)
                {
                    total_month[0, 0] += total_day[0, 0] / 30;
                    total_day[0, 0] = total_day[0, 0] % 30;
                }
            }

            if (total_day[0, 1] >= 30)
            {
                if (total_day[0, 1] == 30 || total_day[0, 1] == 31)
                {
                    total_month[0, 1]++;
                    total_day[0, 1] = 0;
                }

                if (total_day[0, 1] > 31)
                {
                    total_month[0, 1] += total_day[0, 1] / 30;
                    total_day[0, 1] = total_day[0, 1] % 30;
                }
            }

            if (total_day[0, 2] >= 30)
            {
                if (total_day[0, 2] == 30 || total_day[0, 2] == 31)
                {
                    total_month[0, 2]++;
                    total_day[0, 2] = 0;
                }

                if (total_day[0, 2] > 31)
                {
                    total_month[0, 2] += total_day[0, 2] / 30;
                    total_day[0, 2] = total_day[0, 2] % 30;
                }
            }

            if (total_day[1, 0] >= 30)
            {
                if (total_day[1, 0] == 30 || total_day[1, 0] == 31)
                {
                    total_month[1, 0]++;
                    total_day[1, 0] = 0;
                }

                if (total_day[1, 0] > 31)
                {
                    total_month[1, 0] += total_day[1, 0] / 30;
                    total_day[1, 0] = total_day[1, 0] % 30;
                }
            }

            if (total_day[1, 1] >= 30)
            {
                if (total_day[1, 1] == 30 || total_day[1, 1] == 31)
                {
                    total_month[1, 1]++;
                    total_day[1, 1] = 0;
                }

                if (total_day[1, 1] > 31)
                {
                    total_month[1, 1] += total_day[1, 1] / 30;
                    total_day[1, 1] = total_day[1, 1] % 30;
                }
            }

            if (total_day[1, 2] >= 30)
            {
                if (total_day[1, 2] == 30 || total_day[1, 2] == 31)
                {
                    total_month[1, 2]++;
                    total_day[1, 2] = 0;
                }

                if (total_day[1, 2] > 31)
                {
                    total_month[1, 2] += total_day[1, 2] / 30;
                    total_day[1, 2] = total_day[1, 2] % 30;
                }
            }

            total_point[0] = total_month[0, 0] * Util.getCareerMonthPoint("기본경력", "가경력") + total_day[0, 0] * Util.getCareerDayPoint("기본경력", "가경력");
            total_point[1] = total_month[0, 1] * Util.getCareerMonthPoint("기본경력", "나경력") + total_day[0, 1] * Util.getCareerDayPoint("기본경력", "나경력");
            total_point[2] = total_month[0, 2] * Util.getCareerMonthPoint("기본경력", "다경력") + total_day[0, 2] * Util.getCareerDayPoint("기본경력", "다경력");
            total_point[3] = total_month[1, 0] * Util.getCareerMonthPoint("초과경력", "가경력") + total_day[1, 0] * Util.getCareerDayPoint("초과경력", "가경력");
            total_point[4] = total_month[1, 1] * Util.getCareerMonthPoint("초과경력", "나경력") + total_day[1, 1] * Util.getCareerDayPoint("초과경력", "나경력");
            total_point[5] = total_month[1, 2] * Util.getCareerMonthPoint("초과경력", "다경력") + total_day[1, 2] * Util.getCareerDayPoint("초과경력", "다경력");

            double total = 0.0;
            double btotal = 0.0;
            double atotal = 0.0;

            if (total_month[0, 0] / 12 >= 16)
            {
                btotal = Util.getCareerMaxPoint("기본경력", "가경력");
            }
            else if (total_month[0, 1] / 12 >= 16)
            {
                btotal = Util.getCareerMaxPoint("기본경력", "나경력");
            }
            else if (total_month[0, 2] / 12 >= 16)
            {
                btotal = Util.getCareerMaxPoint("기본경력", "다경력");
            }
            else
            {
                btotal = total_point[0] + total_point[1] + total_point[2];
            }

            if (total_month[1, 0] / 12 >= 5)
            {
                atotal = Util.getCareerMaxPoint("초과경력", "가경력");
            }
            else if (total_month[1, 1] / 12 >= 5)
            {
                atotal = Util.getCareerMaxPoint("초과경력", "나경력");
            }
            else if (total_month[1, 2] / 12 >= 5)
            {
                atotal = Util.getCareerMaxPoint("초과경력", "다경력");
            }
            else
            {
                atotal = total_point[3] + total_point[4] + total_point[5];
            }
            
            total = btotal + atotal;                 
            
            if (total > 70.0) total = 70.0;
            
            lblTotalPoint.Text = total.ToString("#0.000");
            lnkSave.Enabled = true;
        }

        private void lnkSave_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                //트랜잭션 시작
                DBUtil.beginTans();

                //기존데이터 삭제
                DBUtil.deleteFromCareerTable(formParent.txtPCode.Text);

                //새로 입력
                for (int i = 0; i < tbl.Rows.Count; i++)
                {
                    ArrayList data = new ArrayList();
                    data.Add(formParent.txtPCode.Text);
                    data.Add(tbl.Rows[i][0].ToString());
                    data.Add(tbl.Rows[i][1].ToString());
                    data.Add(tbl.Rows[i][2].ToString());
                    data.Add(DateTime.Parse(tbl.Rows[i][3].ToString()));
                    data.Add(DateTime.Parse(tbl.Rows[i][4].ToString()));
                    data.Add(DateTime.Parse(tbl.Rows[i][5].ToString()));
                    data.Add(DateTime.Parse(tbl.Rows[i][6].ToString()));
                    data.Add(Int32.Parse(tbl.Rows[i][7].ToString()));
                    data.Add(Int32.Parse(tbl.Rows[i][8].ToString()));
                    data.Add(Double.Parse(tbl.Rows[i][9].ToString()));
                    data.Add(Double.Parse(tbl.Rows[i][10].ToString()));
                    data.Add(Double.Parse(tbl.Rows[i][11].ToString()));
                    data.Add(DateTime.Now);

                    DBUtil.insertCareerInfo(data);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");
                DBUtil.rollBack();
                return;
            }

            DBUtil.commit();
            MessageBox.Show("저장하였습니다.    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            string total_point = lblTotalPoint.Text;
            if (total_point.Equals("-"))
            {
                formParent.txtCareerpoint.Text = "0.0";
            }
            else
            {
                formParent.txtCareerpoint.Text = total_point;
            }
            this.Close();
        }

    }
}
